<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>table模块快速使用</title>
    <link rel="stylesheet" href="../layui/css/layui.css" media="all">
</head>
<body>
<div class="layui-tab">
    <ul class="layui-tab-title">
        <li class="layui-this" id="goodsMaster">已结账订单</li>
        <li id="waybill">结算历史</li>
    </ul>
    <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
            <table class="layui-hide" id="testTable" lay-filter="testTable"></table>
        </div>
        <div class="layui-tab-item">
            <div class="layui-form toolbar">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <input id="number" class="layui-input" type="text" placeholder="运输单编号"/>
                    </div>
                    <div class="layui-inline">
                        <button id="btnSearch" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
                    </div>
                </div>
            </div>
            <table class="layui-hide" id="waybillTable" lay-filter="waybillTable"></table>
        </div>
    </div>
</div>

<!--<script type="text/html" id="toolbarDemo">-->
<!--    <div class="layui-btn-container">-->
<!--        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>-->
<!--        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>-->
<!--        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>-->
<!--    </div>-->
<!--</script>-->
<!--<script type="text/html" id="toolbar">-->
<!--    <div class="layui-btn-container">-->
<!--        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>-->
<!--        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>-->
<!--    </div>-->
<!--</script>-->

<script type="text/html" id="barDemo">
    <button class="layui-btn layui-btn-xs layui-btn-radius" lay-event="add">去结算</button>
</script>

<script type="text/html" id="barTwo">
    <a class="layui-btn layui-btn-radius layui-btn-warm layui-btn-xs "  lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs layui-btn-radius"  lay-event="del">删除</a>
</script>

<script src="../layui/layui.js" charset="utf-8"></script>

<script>
    // 要使用的layui模块
    layui.use(['layer', 'form', 'table', 'laydate', 'element'], function () {
        var layer = layui.layer; // 获得layer模块
        var form = layui.form; // 获得form模块
        var table = layui.table; // 获得table模块
        var laydate = layui.laydate; // 获得laydate模块
        var element = layui.element; // 获得element模块（和导航、tab等有关）
        var $ = layui.$; // 调用JQuery方法时
        var laytpl = layui.laytpl;
        {
            laydate.render({
                elem: '#startCarryTime',
                type: 'datetime',
                min: minDate()
            });
            laydate.render({
                elem: '#endCarryTime',
                type: 'datetime',
                min:  minDate()
            });
            laydate.render({
                elem: '#startTime',
                type: 'datetime'
            });
            laydate.render({
                elem: '#endTime',
                type: 'datetime'
            });
            laydate.render({
                elem: '#waybillDate',
                type: 'datetime'
            });

            // 设置最小可选的日期
            function minDate(){
                var now = new Date();
                return now.getFullYear()+"-" + (now.getMonth()+1) + "-" + now.getDate();
            }
        }
        // 查询用对象
        var MgrSettle = {
            tableId: "waybillTable",    //表格id
            condition: {
                number: "",
            }
        };
        // 查询请求内容
        MgrSettle.search = function () {
            var queryData = {};
            queryData['number'] = $("#number").val();
            table.reload(MgrSettle.tableId, {where: queryData});
        };
        // 点击查询按钮
        $('#btnSearch').click(function () {
            MgrSettle.search();
        });
        //自定义验证规则
        form.verify({
            title: function (value) {
                if (value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            }
            , word: [
                /^[A-Za-z0-9]+$/
                , '请输入正确的编号'
            ]
            , number: [
                /^[0-9]+(.[0-9]{1,5})?$/
                , '请输入正确的数字'
            ]
            , name: [
                /^[\u4E00-\u9FA5A-Za-z]+$/
                , '请填写正确的姓名'
            ]
            , carNo: [
                /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/
                , '请输入正确的车牌号'
            ]
            , content: function (value) {
                layedit.sync(editIndex);
            }
        });
        //第一个实例
        var tableIns = table.render({
            elem: '#testTable' // 给table设置id或class，方便layui调用该元素
            , height: 'full-100' // 窗口高度-100
            , url: '/settlement/C' // 数据接口
            // ,method: 'post' //如果无需自定义HTTP类型，可不加该参数
            , page: {
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip']
                ,curr: 1
                ,groups: 3
                ,limit: 10
            } // 开启分页
            , cellMinWidth: 80 // 全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , skin: 'line' // 行边框风格
            ,even: true // 开启隔行背景
            // ,size: 'sm' // 小尺寸的表格
            , totalRow: true // 开启合计功能
            , toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
            , defaultToolbar: ['filter', 'exports', 'print', { // 列过滤、导出按钮、打印按钮
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]
            , title: '货运表'// 表名
            // 列信息
            , cols: [[ //表头
                // {type:'radio', fixed: 'left'} // 开启单选框
                {type: 'checkbox', fixed: 'left'} // 开启复选框
                , {field: 'goodsBillCode', title: '货运单编号', fixed: 'left', sort: true, totalRowText: '合计'}
                , {field: 'sendGoodsCustomer', title: '发货客户'}
                , {field: 'receiveGoodsCustomer', title: '收货客户', totalRow: false}
                , {field: 'receiveGoodsAddr', title: '收货地址', totalRow: false}
                , {field: 'validity', title: '有效性', totalRow: false}
                , {field: 'ifSettleAccounts', title: '运单状态'}
                , {field: 'carriage', title: '运费', totalRow: true}
                , {field: 'insurance', title: '保险费', totalRow: true}
                , {field: 'acceptStation', title: '接货点', totalRow: true}
                , {field: 'sendGoodsCustomerMobile', title: '发货客户手机', totalRow: true}
                , {field: 'receiveGoodsCustomerMobile', title: '收货客户手机', totalRow: true}
                , {field: 'remark', title: '备注', totalRow: true}
                , {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 100}
            ]]
        });
        var tableIns = table.render({
            elem: '#waybillTable' // 给table设置id或class，方便layui调用该元素
            , height: 'full-150' // 窗口高度-100
            , url: '/settlement/getDriverBalanceByState' // 数据接口
            // ,method: 'post' //如果无需自定义HTTP类型，可不加该参数
            , page: true
            , limit: 10
            , cellMinWidth: 80 // 全局定义常规单元格的最小宽度，layui 2.2.1 新增
            , skin: 'line' // 行边框风格
            ,even: true // 开启隔行背景
            // ,size: 'sm' // 小尺寸的表格
            , totalRow: true // 开启合计功能
            , toolbar: '#toolbar' //开启头部工具栏，并为其绑定左侧模板
            //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
            , defaultToolbar: ['filter', 'exports', 'print', { // 列过滤、导出按钮、打印按钮
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]
            , title: '司机结算表'// 表名
            // 列信息
            , cols: [[ //表头
                // {type:'radio', fixed: 'left'} // 开启单选框
                {type: 'checkbox', fixed: 'left'} // 开启复选框
                , {field: 'backBillCode', title: '运输单编号', fixed: 'left', sort: true, totalRowText: '合计'}
                , {field: 'balanceType', title: '结算状态'}
                , {field: 'needPayment', title: '应付金额',}
                , {field: 'carryFee', title: '承运费'}
                , {field: 'driver',title: '司机名称',templet:'<div>{{d.driver.driverName}}</div>'}
                , {field: 'bindInsurance', title: '定装费', totalRow: false}
                , {field: 'addCarriage', title: '加运费', totalRow: false}
                , {field: 'payedMoney', title: '已付金额'}
                , {field: 'balance', title: '余额', totalRow: false}
                , {field: 'insurance', title: '保险费', totalRow: true}
                , {field: 'dispatchFerviceFee', title: '配载服务费', totalRow: true}
                , {fixed: 'right', title: '操作', toolbar: '#barTwo', width: 250}
            ]]
        });




        //!!! 注意：批量删除按钮在script里，必须使用以下格式才能不出点击重置后无效的bug
        //批量删除
        $('body').on('click', '#btnBatchDelete', function() {
            var checkStatus = table.checkStatus('testTable'),
                data = checkStatus.data,
                keys ="";
            if(data.length > 0) {
                for (var i in data) {
                    keys+=data[i].ddid+",";
                }
                keys = keys.substring(0,keys.length-1);
                console.log(keys);
                layer.confirm('确定删除选中的数据？',{title: '提示信息'},function(index) {
                    $.post('/settlement/searchDriver'+keys,function(data){
                        if (data.code==0) {
                            tableIns.reload();
                            layer.msg(data.msg);
                            layer.close(index);
                        }
                    })
                });
            }else{
                layer.msg("请先选择需要删除的数据");
            }
        });



        // 监听行双击事件
        table.on('rowDouble(testTable)', function (obj) {
            console.log(obj.tr) //得到当前行元素对象
            console.log(obj.data) //得到当前行数据
        });

        table.on('checkbox(testTable)', function (obj) {

            // 复选框监听
            console.log(obj.checked); //当前是否选中状态
            console.log(obj.data); //选中行的相关数据
            console.log(obj.type); //如果触发的是全选，则为：all，如果触发的是单选，则为：one
        });

        //头工具栏事件
        table.on('toolbar(testTable)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                case 'getCheckData':
                    var data = checkStatus.data;
                    layer.alert(JSON.stringify(data));
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：' + data.length + ' 个');
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选' : '未全选');
                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
            }
            ;
        });

        table.on('tool(testTable)',function (obj) {
            var data = obj.data;
            var gmid = data['gmid'];
            alert(data['gmid']);
            if (obj.event === 'add'){
                $("#waybillForm")[0].reset();
                layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "添加运单",
                    area: ['420px','520px'],
                    btn:['取消'],
                    content: $("#balanceDiv")  //引用的弹出层的页面层的方式加载修改表单
                });
                addWaybill(gmid);
            }
        })

        function addWaybill(gmid){
            form.on('submit(ok)',function (data) {
                $.ajax({
                    url: '/settlement/doSettlement',
                    type: 'POST',
                    data: {
                        gmid: gmid
                        ,carryFee: data.field.carryFee
                        ,bindInsurance: data.field.bindInsurance
                        ,addCarriage: data.field.addCarriage
                        ,payedMoney:  data.field.payedMoney
                        ,dispatchFerviceFee: data.field.dispatchFerviceFee
                        ,needPayment: data.field.needPayment
                    },
                    success:function (result) {
                        var code = result.code;
                        if (code == 0){
                            layer.load(2);
                            layer.msg(result.msg,{icon: 6});
                            //修改成功不进行跳转
                            layer.closeAll();//关闭所有的弹出层
                            window.location.reload();
                        }else {
                            layer.msg(result.msg,{inco:5});
                        }
                    }
                });
                return false;
            })
        }

        //监听工具条
        table.on('tool(waybillTable)', function (obj) {
            var data = obj.data;
            var dsmid = data['dsmid'];
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                   $.ajax({
                       url: "/settlement/deleteDriverBalance",
                       type: "POST",
                       data : {
                           dbid: dsmid
                       },
                       success: function (result) {
                           if(result.code == 0){
                               obj.del();
                               //关闭弹框
                               layer.close(index);
                               layer.msg(result.msg,{icon: 6})
                               window.location.reload();
                           }else {
                               layer.msg(result.msg,{icon: 5})
                           }
                       }
                   })
                });
            }
            else if (obj.event === 'edit') {
                // var predata = obj.data;    //获得当前行数据
                // console.log(obj['driver']);
                var data = obj.data;
                $('#carry').val(data['carryFee']);
                $('#bind').val(data['bindInsurance']);
                $('#payMoney').val(data['payedMoney']);
                $('#Carriage').val(data['endCarryTime']);
                $('#dispatch').val(data['dispatchFerviceFee']);
                $('#insurance').val(data['insurance']);
                layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "添加运单",
                    area: ['800px','600px'],
                    btn:['取消'],
                    content: $("#updateDiv")  //引用的弹出层的页面层的方式加载修改表单
                });
                //发送请求
                setFormValue(data);
            }
        });
        //监听弹出框表单提交，message修啊界面的表单数据，sumbit（是修改按钮的而绑定）
        function setFormValue(olddata) {
            form.on('submit(yes)',function (data) {
                // console.log(data.field);
                $.ajax({
                    url: '/settlement/updateBalance',
                    type: 'POST',
                    data: {
                        'dsmid': olddata['dsmid']
                        ,'carryFee': data.field.carryFee
                        ,'bindInsurance': data.field.bindInsurance
                        ,'addCarriage': data.field.addCarriage
                        ,'dispatchFerviceFee':  data.field.dispatchFerviceFee
                        ,'insurance': data.field.insurance
                        ,'payedMoney': data.field.payedMoney
                        ,'balanceTime': olddata['balanceTime']
                        ,'balance': olddata['balance']
                        ,'needPayment': olddata['needPayment']
                        ,'backBillCode': olddata['backBillCode']
                        ,'driverPkid': olddata['driverPkid']
                        ,'flag': olddata['flag']
                        ,'balanceType': olddata['balanceType']
                    },
                    success:function (result) {
                        console.log(result);
                        var code = result.code;
                        if (code == 0){
                            layer.closeAll("Loading");
                            layer.load(2);
                            layer.msg(result.msg,{icon: 6});
                            layer.closeAll();//关闭所有的弹出层
                            window.location.reload();
                        }else {
                            layer.msg(result.msg,{inco:5});
                        }
                    }
                });
                return false;
            })
        }
        //应付金额显示
        {
            $('#dispatchFerviceFee').bind('input propertychange',function () {
                var bindInsurance = parseFloat($('#bindInsurance').val());
                var carryFee = parseFloat($('#carryFee').val());
                var dispatch = parseFloat($('#dispatchFerviceFee').val());
                var addCarriage = $('#addCarriage').val();
                if (carryFee!=""&&bindInsurance!=""&&dispatch!=""){
                    if (addCarriage=="" || addCarriage==null){
                        addCarriage=0;
                    } else {
                        addCarriage = parseFloat($('#addCarriage').val());
                    }
                    var needPay = bindInsurance+carryFee+addCarriage+dispatch;
                    $('#needPay').val(needPay);
                }
            })
        }
        
    });


</script>
<!--这是弹出层的表单信息
表单的id用于表单的选择，style是在本页隐藏，只有点击编辑才会弹出-->
<div id="balanceDiv" style="display: none;">
    <fieldset class="layui-elem-field layui-field-title" lay-filter="driver" style="margin-top: 50px;">
        <legend>结算信息填写</legend>
    </fieldset>
    <form class="layui-form layui-form-pane" id="waybillForm" action="" style="margin-left: 50px">
        <div class="layui-form-item">
            <label class="layui-form-label">应付金额</label>
            <div class="layui-input-inline" >
                <input type="text" style="color: red"  readonly  unselectable="on"  id="needPay" name="needPayment" lay-verify="number" placeholder="0" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">承运费</label>
            <div class="layui-input-inline">
                <input type="text" id="carryFee" name="carryFee" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">定装费</label>
            <div class="layui-input-inline">
                <input type="text" id="bindInsurance" name="bindInsurance" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">加运费</label>
            <div class="layui-input-inline">
                <input type="text" name="addCarriage" id="addCarriage" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">配载服务费</label>
            <div class="layui-input-inline">
                <input type="text" id="dispatchFerviceFee" name="dispatchFerviceFee" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">已付金额</label>
            <div class="layui-input-inline">
                <input type="text" name="payedMoney" id="payedMoney" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <button class="layui-btn" lay-submit="" lay-filter="ok" >确认提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </form>
</div>
<div id="updateDiv" style="display: none">
    <fieldset class="layui-elem-field layui-field-title" lay-filter="driver" style="margin-top: 50px;">
        <legend>结算单信息修改</legend>
    </fieldset>
    <form class="layui-form layui-form-pane" id="updateWaybillForm" action="" style="margin-left: 50px">
        <div class="layui-form-item">
            <label class="layui-form-label">承运费</label>
            <div class="layui-input-inline">
                <input type="text" id="carry" name="carryFee" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">定装费</label>
            <div class="layui-input-inline">
                <input type="text" id="bind" name="bindInsurance" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">加运费</label>
            <div class="layui-input-inline">
                <input type="text" id="Carriage" name="addCarriage" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">配载服务费费</label>
            <div class="layui-input-inline">
                <input type="text" id="dispatch" name="dispatchFerviceFee" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">已付金额</label>
            <div class="layui-input-inline">
                <input type="text" id="payMoney" name="payedMoney" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
        </div>
            <div class="layui-form-item">
                <label class="layui-form-label">保险费</label>
                <div class="layui-input-inline">
                    <input type="text" id="insurance" name="insurance" lay-verify="number" placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <button class="layui-btn" lay-submit="" lay-filter="yes" >确认提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </form>
</div>
</body>
</html>